package main

import (
	"fmt"
	"image"
	"image/color"

	"gitee.com/xntk2381/frog"
	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/ebitenutil"
)

const (
	screenWidth  = 520
	screenHeight = 550
)

// Game 实现ebiten.Game接口
type Game struct {
	env *frog.Env
	img image.Image
}

// NewGame 创建新的游戏实例
func NewGame() *Game {
	env := frog.NewEnv()
	go env.Run()

	return &Game{
		env: env,
	}
}

// Update 更新游戏状态
func (g *Game) Update() error {
	// 这里可以添加游戏状态更新逻辑
	return nil
}

// Draw 绘制游戏画面
func (g *Game) Draw(screen *ebiten.Image) {
	// 绘制背景
	screen.Fill(color.RGBA{255, 255, 255, 255})

	// 绘制食物
	g.env.DrawFood(screen)

	// 绘制青蛙
	g.env.Mu.Lock()
	defer g.env.Mu.Unlock()
	for _, frog := range g.env.Frogs {
		frog.Show(screen)
	}

	// 显示信息
	msg := fmt.Sprintf("Frogs: %d, Food: %d", countFrog(g.env), countFood(g.env))
	ebitenutil.DebugPrint(screen, msg)
}

// Layout 设置游戏窗口大小
func (g *Game) Layout(outsideWidth, outsideHeight int) (int, int) {
	return screenWidth, screenHeight
}

func countFrog(env *frog.Env) int {
	count := 0
	for _, frog := range env.Frogs {
		if frog.Alive {
			count++
		}
	}
	return count
}

// countFood 计算剩余食物数量
func countFood(env *frog.Env) int {
	count := 0
	for x := 0; x < env.ENV_XSIZE; x++ {
		for y := 0; y < env.ENV_YSIZE; y++ {
			if env.Foods[x][y] > 0 {
				count++
			}
		}
	}
	return count
}

func main() {
	game := NewGame()

	ebiten.SetWindowSize(screenWidth, screenHeight)
	ebiten.SetWindowTitle("Frog Simulation")

	if err := ebiten.RunGame(game); err != nil {
		panic(err)
	}
}
